package com.easy.common.aspect;


import com.easy.common.annotation.LogRecord;
import com.easy.common.bean.SysLog;
import com.easy.common.service.ILogService;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;


@Aspect
@Component
public class LogAspect {
    @DubboReference
    ILogService logService;
    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.easy.common.annotation.LogRecord)")
    public void logPoint(){}

    @Around("logPoint()")
    public Object log(ProceedingJoinPoint point) throws Throwable {
        //指定被代理对象的方法   result就是被代理对象的方法的返回值
        Object result=point.proceed();

        MethodSignature signature = (MethodSignature) point.getSignature();
        //获取到切点方法
        Method method = signature.getMethod();
        //获取方法上标记的注解内容
        LogRecord annotation = method.getAnnotation(LogRecord.class);
        String module = annotation.module();
        String info= annotation.info();

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteAddr();

        String username=request.getHeader("actionUsername");//需要在gateway模块中获取设置的
        username="张三";

        SysLog log=new SysLog();
        log.setIp(ip);
        log.setModule(module);
        log.setOperator(username);
        log.setDescription(info);
        logService.log(log);
        return result;
    }
}